package cn.hg.solon.youcan.framework.directive.common;

import cn.hg.solon.youcan.common.constant.CacheConstants;
import cn.hg.solon.youcan.framework.cache.RedisCacheTagsService;
import cn.hg.solon.youcan.framework.directive.BaseDirective;
import cn.hg.solon.youcan.system.service.ConfigService;
import com.jfinal.template.Env;
import com.jfinal.template.TemplateException;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import org.dromara.hutool.core.text.StrValidator;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.List;
import java.util.function.Supplier;

/**
 * 获取参数列表指令：#CONFIGS('type')
 *
 * @author 胡高
 */
@Component("view:" + ConfigsDirective.DIRECTIVE_NAME)
public class ConfigsDirective extends BaseDirective {

    public static final String DIRECTIVE_NAME = "CONFIGS";

    @Inject
    private ConfigService configService;

    @Inject
    private RedisCacheTagsService cacheService;

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {
        // 参数类型
        String type = this.getParaToString(0, scope);
        if (StrValidator.isBlank(type)) {
            throw new TemplateException("The parameter of #" + DIRECTIVE_NAME + " directive can not be blank",
                    this.location);
        }

        @SuppressWarnings({"rawtypes"})
        List list = this.cacheService.getOrStoreTag(DIRECTIVE_NAME + ":" + type, List.class,
                CacheConstants.CACHE_SECONDS_ONE_DAY, new Supplier<List>() {
                    @Override
                    public List get() {
                        /*
                         * 查询字典类型列表
                         */
                        return ConfigsDirective.this.configService.listByType(type);
                    }

                }, CacheConstants.SYS_CONFIG_TAG);

        scope.set(this.getPara("var", scope, DIRECTIVE_NAME.toLowerCase()), list);
    }

}
